#!/bin/bash

# updateLastEdited.sh - updated the time files in a given directory were
#                       last updated

TARGET_DIR="/var/www/tcdb/html"
KEYWORD="Last edited"

# For each PHP file in $TARGET_DIR...
for FILE in $(find $TARGET_DIR -type f -name '*.php')
do
  # Find modification time and date

  CC=`stat -c %y $FILE | awk '{print $1}' | cut -c1,2`
  YY=`stat -c %y $FILE | awk '{print $1}' | cut -c3,4`
  MM=`stat -c %y $FILE | awk '{print $1}' | cut -d- -f2`
  DD=`stat -c %y $FILE | awk '{print $1}' | cut -d- -f3`
  hh=`stat -c %y $FILE | awk '{print $2}' | cut -d: -f1`
  mm=`stat -c %y $FILE | awk '{print $2}' | cut -d: -f2`
  SS=`stat -c %y $FILE | awk '{print $2}' | cut -d: -f3 | cut -d. -f1`
  
  # Find the "real" modification time from the output of ls
  CURRENT_MOD_DATE=`ls -l $FILE | grep -o '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}'`

  # Find the modification date in the $KEYWORD part of the file
  OLD_MOD_DATE=`grep "$KEYWORD" $FILE | grep -o '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}'`

  # Replace $OLD_MOD_DATE with $CURRENT_MOD_DATE on everyline where $KEYWORD appears
  sed -i "/$KEYWORD/s/$OLD_MOD_DATE/$CURRENT_MOD_DATE/g" $FILE

  # Finally, "re-touch" the file so that we replace the modification time with the old mod time
  touch -t "$CC$YY$MM$DD$hh$mm.$SS" $FILE
done

exit 0
